<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Basic Swing components II</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Swing, basic components, Java, tutorial, JList, JTextArea, JTextPane">
<meta name="description" content="This part of the Java Swing tutorial continues covering basic Swing components.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Basic Swing components II</h1>


<p>
Swing components are basic building blocks of an application. Swing toolkit has a
wide range of various components. Buttons, check boxes, sliders, list boxes etc. 
Everything a programmer needs for his job. In this section of the tutorial, 
we will describe several useful components.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>


<h2>JList Component</h2>

<p>
<code>JList</code> is a  component that displays a list of 
objects. It allows the user to select one or more items.
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class ListExample extends JFrame {

    private JLabel label;
    private JList list;


    public ListExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();

        String[] fonts = ge.getAvailableFontFamilyNames();

        list = new JList(fonts);
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    String name = (String) list.getSelectedValue();
                    Font font = new Font(name, Font.PLAIN, 12);
                    label.setFont(font);
                }
            }
        });

        JScrollPane pane = new JScrollPane();
        pane.getViewport().add(list);
        pane.setPreferredSize(new Dimension(250, 200));
        panel.add(pane);

        label = new JLabel("Aguirre, der Zorn Gottes");
        label.setFont(new Font("Serif", Font.PLAIN, 12));
        add(label, BorderLayout.SOUTH);


        add(panel);

        pack();
        setTitle("JList");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ListExample ex = new ListExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>


<p>
In our example, we will display a <code>JList</code> and a 
<code>JLabel</code> components. The list component contains 
a list of all available font family names on our system.
If we select an item from the list, the label will be displayed in a 
font, we have chosen.
</p>

<pre class="explanation">
GraphicsEnvironment ge = 
    GraphicsEnvironment.getLocalGraphicsEnvironment();

String[] fonts = ge.getAvailableFontFamilyNames();
</pre>

<p>
Here we obtain all possible font family names on our system. 
</p>

<pre class="explanation">
list = new JList(fonts);
</pre>

<p>
We create a <code>JList</code> component. 
</p>

<pre class="explanation">
public void valueChanged(ListSelectionEvent e) {
    if (!e.getValueIsAdjusting()) {
</pre>

<p>
Events in list selection are grouped.
We receive events for both selecting and deselecting.
To filter only the selecting events, we use the 
<code>getValueIsAdjusting()</code> method.
</p>

<pre class="explanation">
String name = (String) list.getSelectedValue();
Font font = new Font(name, Font.PLAIN, 12);
label.setFont(font);
</pre>

<p>
We get the selected item and set a new font for the label. 
</p>

<pre class="explanation">
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
</pre>

<p>
<code>JLabel</code> component is not scrollable by default. We put 
the list into the <code>JScrollPane</code> to make it scrollable.
</p>


<img src="/img/gui/javaswing/jlist.png" alt="JList component">
<div class="figure">Figure: JList</div>


<h2>JTextArea component</h2>

<p>
A <code>JTextArea</code> is a multi-line text area that displays
plain text. It is lightweight component for working with text. The component 
does not handle scrolling. For this task, we use <code>JScrollPane</code> component. 
</p>

<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaExample extends JFrame {

    public TextAreaExample() {
        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JScrollPane pane = new JScrollPane();
        JTextArea area = new JTextArea();

        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        area.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

        pane.getViewport().add(area);
        panel.add(pane);

        add(panel);

        setTitle("JTextArea");
        setSize(new Dimension(350, 300));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TextAreaExample ex = new TextAreaExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The example shows a simple <code>JTextArea</code> component.
</p>

<pre class="explanation">
JTextArea area = new JTextArea(); 
</pre>

<p>
This is the constructor of the <code>JTextArea</code> component. 
</p>

<pre class="explanation">
area.setLineWrap(true);
</pre>

<p>
Make the lines wrapped, if they are too long to fit the width.
</p>

<pre class="explanation">
area.setWrapStyleWord(true);
</pre>

<p>
Here we specify, how is line going to be wrapped. In our case, lines will be 
wrapped at word boundaries, whitespaces.
</p>

<pre class="explanation">
area.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
</pre>

<p>
We put some border around the text in the component. 
</p>

<pre class="explanation">
pane.getViewport().add(area);
</pre>

<p>
To make the text scrollable, we put the <code>JTextArea</code> 
component into the <code>JScrollPane</code> component. 
</p>


<img src="/img/gui/javaswing/jtextarea.png" alt="JTextArea component">
<div class="figure">Figure: JTextAra</div>


<h2>JTextPane component</h2>


<p>
<code>JTextPane</code> component is a more advanced component 
for working with text. The component can do some complex formatting 
operations over the text. It can display also HTML documents. 
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.Dimension;

import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;


public class TextPaneExample extends JFrame {

    public TextPaneExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JScrollPane pane = new JScrollPane();
        JTextPane textpane = new JTextPane();

        textpane.setContentType("text/html");
        textpane.setEditable(false);

        String cd = System.getProperty("user.dir") + "/";

        try {
            textpane.setPage("File:///" + cd + "test.html");
        } catch (IOException e) {
            System.out.println("Exception: " + e);
        }

        textpane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

        pane.getViewport().add(textpane);
        panel.add(pane);

        add(panel);

        setTitle("JTextPane");
        setSize(new Dimension(380, 320));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TextPaneExample ex = new TextPaneExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
This is the HTML code, that we are loading into the 
<code>JTextPane</code> component. The component does not
handle scrolling. 
</p>

<pre class="code">
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;A simple html document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h2&gt;A simple html document&lt;/h2&gt;


&lt;p&gt;
&lt;b&gt;JTextPane&lt;/b&gt; can display html documents. 
&lt;/p&gt;

&lt;br&gt;

&lt;pre&gt;
 JScrollPane pane = new JScrollPane();
 JTextPane textpane = new JTextPane(); 

 textpane.setContentType("text/html");
 textpane.setEditable(false);
&lt;/pre&gt;

&lt;br&gt;
&lt;small&gt;The Java Swing tutorial, 2010&lt;/small&gt;

&lt;/body&gt;

&lt;/html&gt;
</pre>


<p>
In our example we show a <code>JTextPane</code> component and 
load a html document. Example shows formatting capabilities 
of the component. 
</p>

<pre class="explanation">
JTextPane textpane = new JTextPane(); 

textpane.setContentType("text/html");
textpane.setEditable(false);
</pre>

<p>
We create a <code>JTextPane</code> component, set the content 
of the component to be a HTML document and disable
editing.
</p>

<pre class="explanation">
String cd = System.getProperty("user.dir") + "/";
</pre>

<p>
Here we determine the current working directory of the user. The HTML 
document is located there. 
</p>

<pre class="explanation">
try {
    textpane.setPage("File:///" + cd + "test.html");
} catch (IOException e) {
    System.out.println("Exception: " + e);
}
</pre>

<p>
We load a HTML document into the pane. 
</p>


<img src="/img/gui/javaswing/jtextpane.png" alt="JTextPane component">
<div class="figure">Figure: JTextPane</div>


<p>
In this chapter, we have continued covering basic Swing components.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 14, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
